<?php
declare (strict_types=1);

namespace app\common\model\questionnaire;

use cores\BaseModel;

/**
 * 问卷记录表模型
 * Class Questionnaire
 * @package app\common\model\questionnaire
 */
class Questionnaire extends BaseModel
{
    // 定义表名
    protected $name = 'questionnaire';

    // 定义主键
    protected $pk = 'questionnaire_id';

    /**
     * 追加字段
     * @var array
     */
    protected $append = ['total_count', 'total_fraction'];

    /**
     * 详情
     * @param $where
     * @param array $with
     * @return array|static|null
     */
    public static function detail($where, array $with = [])
    {
        return static::get($where, $with);
    }

    /**
     * 验证问卷名称是否重复
     * @param string $phone
     * @return bool
     */
    public static function checkQuestionnaireNameExist(string $name)
    {
        return (bool)static::withoutGlobalScope()
            ->where('questionnaire_name', '=', $name)
            ->where('is_delete', '=', 0)
            ->value('questionnaire_name');
    }

    public function getTotalCountAttr($value, $data)
    {
        return (new Topic())->where([
            'questionnaire_id' => $data['questionnaire_id'],
            'is_delete' => 0,
        ])->count();
    }

    public function getTotalFractionAttr($value, $data)
    {
//        return (new Topic())->where([
//            'questionnaire_id' => $data['questionnaire_id'],
//            'is_delete' => 0,
//        ])->sum('fraction');
        return 100;
    }
}
